<?php

namespace Modules\Core\View\Components\Inputs;

use Illuminate\Support\Str;
use Illuminate\View\Component;

class XSelect extends Component
{
    public $name;
    public $options;
    public $type;
    public $label;
    public $value;
    public $search;
    public $optionHtml;
    public $isSimpleOption; //是否是简单options, 无键值即是
    public $required;
    public $max; // 选项上限，默认0不限
    public $valueField; // 默认值对应的数据库字段，单字段检索效率高


    public $iptkey;

    /**
     * Create a new component instance.
     *
     * @return void
     */
    public function __construct($name, $options, $value = '', $required=false, $max = 0, $valueField = '')
    {
        $this->name = $name;
        $this->options =  $options;
        $this->required = $required;

        $this->value = $value;
        $this->valueField = $valueField;

        $this->iptkey = Str::random(6);
    }

    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\View\Viewold|string
     */
    public function render()
    {
        return  <<<'blade'
            <script src="/assets/core/xm-select.js"></script>
            <div id="{{ $iptkey }}" style="margin-bottom:50px;width:500px;"></div>
            <script>
                $(function(){
                    layui.use(['admin','util'], function(){
                        var admin = layui.admin,
                            util = layui.util;
                        var defaultSearchValue = '{{ $valueField?$valueField.':':'' }}{{ implode(explode(',',$value), '|')}}';
                        var xselect_{{ $iptkey }} = xmSelect.render({
                            el: '#{{ $iptkey }}',
                            filterable: true,
                            paging: true,
                            name: 'lalalalalala',
                            autoRow: true,
                            layVerify: 'required',
                            tips: '请选择?',
                            max: 0,
                            maxMethod(seles, item){
                                layer.msg(`${item.name}不能选了, 已经超了`)
                            },
                            toolbar: {show: true,showIcon: false},
                            remoteSearch: true,
                            pageSize: 10,
                            remoteMethod: function(val, cb, show, pageIndex){
                                layui.util.request.get('{{ $options }}', {search: val || defaultSearchValue, dataType: 'xselect',value: '{{$value}}'}, function(res){
                                    //回调需要两个参数, 第一个: 数据数组, 第二个: 总页码
                                    cb(res.data, res.meta.last_page)
                                })
                            }
                        })
                    })
                })
            </script>
        blade;
    }

}
